<template>
    <!-- pages_direct_delivery/packet/product_line/index -->
    <view class="container" :style="themeColor">
        <header-bar :config="config"></header-bar>
        <view class="header-wrapper">
            <view class="title">专款专用额度</view>
            <view class="balance">¥{{ DeclarationBalance }}</view>
        </view>
        <search-bar :placeholderText="placeholderText" @searchFn="searchFn"> </search-bar>
        <view class="main-dom product-main">
            <scroll-view class="product-main-nav" scroll-y="true" :style="{ height: listHeight }">
                <nav-tree :tree-data="classifyList" :active-id="activeId" :tagId="tagId" :brandId="brandId"
                    @treeClickEvent="treeClickEvent">
                </nav-tree>
            </scroll-view>
            <view class="product-main-list">
                <product-list v-if="loadOk && ProductLineIds && classifyList.length" ref="swiperIndex"
                    :requestData="requestData" :height="listHeight2" :isHideProImg="isHideProImg" @sku="sku"
                    @amountProp="amountProp" infoType="0" :displayData="displayData" :tempType="0"
                    :wareHouseId="wareHouseId" :ProductLineIds="ProductLineIds" :isOnShow="isOnShow"
                    :isTempCar="isTempCar" @pormotionFn="pormotionFn" @upFavorite="upFavorite" @isUpNum="isUpNum"
                    :isClass="isClass" :isDirect="true" :straight="true" @loadNoMoreBack="loadNoMoreBack">
                </product-list>
            </view>
            <bottom-cart-bar @openCart="openCart" @sunbmitOrder="sunbmitOrder"></bottom-cart-bar>
        </view>

        <!-- 临时购物车 -->
        <uni-popup type="bottom" ref="popCarTip" :safe-area="false">
            <view class="popup-content">
                <view class="popup-title">
                    <text class="popup-title-text">已选商品</text>
                    <text class="popup-title-action" @click="clearCart">清空</text>
                </view>
                <scroll-view scroll-y="true" class="scroll">
                    <view class="cart-item" v-for="(cartItem, index) in list" :key="cartItem.id">
                        <cart-item-product :productInfo="cartItem"></cart-item-product>
                        <cart-item-specs :spaceItem="spaceItem" v-for="(spaceItem, spaceIndex) in cartItem.SubItems"
                            :key="spaceItem.ID"></cart-item-specs>
                    </view>
                </scroll-view>
            </view>
        </uni-popup>

        <!-- 输入订购数量 -->
        <uni-popup ref="popAmountTip" type="center" class="popAmountTip" :animation="false" :maskClick="true">
            <view class="pop-return-box">
                <view class="pop-return-title">
                    <text>输入订购数量</text>
                </view>
                <!-- #ifdef APP -->
                <input confirm-type="search" :auto-focus="true" maxlength="10" type="digit" v-model="popinputAmount"
                    class="btn-input" />
                <!-- #endif -->
                <!-- #ifndef APP -->
                <input confirm-type="search" :focus="isFocus" maxlength="10" :selection-start="selectionStart"
                    :selection-end="selectionEnd" type="digit" v-model="popinputAmount" class="btn-input" />
                <!-- #endif -->

                <view class="pop-action">
                    <view @click="popAmountClose">取消</view>
                    <view @click="popAmountConfirm">确定</view>
                </view>
            </view>
        </uni-popup>

        <!-- 选择规格弹窗 -->
        <uni-popup type="bottom" ref="popSku" @change="skuChange" class="flxedtop">
            <product-spec v-if="showPopSku" :data="optPopup.data" :tempType="tempType" :fresh="optPopup.change"
                :popup-type="optPopup.type" :isDirect="true" :requestData="requestData" :wareHouseId="wareHouseId"
                @changeProductData="changeProductData" @closePopup="closePopup" @addCart="addCart" @addBatch="addBatch"
                @setCarListFunc="setCarListFunc">
            </product-spec>
        </uni-popup>

        <!-- 促销信息 -->
        <uni-popup ref="policyPop" type="bottom" background-color="#fff" :safe-area="false">
            <view class="pop-main">
                <view class="title">
                    <text class="title-text">促销</text>
                    <uni-icons class="icon-close" size="48" type="closeempty" @click="$refs.policyPop.close()">
                    </uni-icons>
                </view>
                <view class="main">
                    <view class="policy-item" v-for="(subitem, index) in pormotionData" :key="index">
                        <text class="policy-name main-color-text icon-gray-2"><text class="cxType"
                                v-if="subitem.DetailList[0].DiscountDetailList.length > 0">{{
                                    subitem.DetailList[0].DiscountDetailList[0].Type == 0 ? "满减" : "折扣"
                                }}</text>{{ subitem.Name }} {{ subitem.Remark }}</text>
                    </view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { mapMutations, mapState, mapGetters } from "vuex"
import { eventBus } from "@/utils/eventBus.js"
import utilsOld from "@/utils/utilsOld.js"
import { getUserCarList } from "@/service/api/member.js"
import { updateCart, getUserTempCarList } from "@/utils/cartUtil.js"
import searchBar from "@/components/common/search-bar.vue"
import { getElementHeight, getElementTop } from "@/uni-sub-base/utils/elementUtil.js"
import { getProductDisplay } from "@/utils/appInit.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
import { GetAccountBalance, GetUserProductLine, GetProductCategoryListByLine } from "@/service/api/product.js"
import navTree from "@/components/product/nav-tree.vue"
import productList from "./product-list.vue"
import productSpec from "@/components/productClass/product-spec.vue"
import bottomCartBar from "./bottom-cart-bar.vue"
import cartItemProduct from "./cart-item-product.vue"
import cartItemSpecs from "./cart-item-specs.vue"

export default {
    components: {
        searchBar,
        navTree,
        productList,
        productSpec,
        bottomCartBar,
        cartItemProduct,
        cartItemSpecs
    },
    data() {
        return {
            loadOk: false,
            list: [],
            config: {
                title: "专区订货",
                back: true,
                color: ["#ffffff"],
                centerSlot: true,
                barPlaceholder: true,
            },
            placeholderText: "请输入商品名称",
            isIos: false,
            listHeight: 0, //list所需高度
            listHeight2: 0, //list所需高度
            classifyList: [], //分类列表
            activeId: -1,
            tagId: "",
            brandId: "",
            DeclarationBalance: 0, //专款专用额度
            requestData: {

            },
            isHideProImg: false,
            displayData: {}, // 商品列表整体显示配置(产品图是否显示等)
            wareHouseId: "",
            ProductLineIds: "", //产品线id
            isOnShow: true,
            isClass: false,
            isTempCar: true,
            showPopSku: false,
            // sku 商品规格弹窗
            optPopup: {
                data: {},
                type: "",
                change: false,
                show: true,
            },
            isUp: true,
            isFocus: false,
            selectionStart: -1,
            selectionEnd: 0,
            popinputAmount: "",
            popite: {},
            popitem: {},
            pormotionData: []
        }
    },
    created() {
        this.config.backgroundColor = [1, this.getThemeColor]
    },
    watch: {
        // todo
    },
    computed: {
        ...mapGetters(["getUpView"]),
    },
    onLoad(e) {
        // todo
    },
    unmounted() {
        eventBus.$off("SET_TEMP_CART", (msg) => {
            if (msg) {
                // todo
            }
        })
    },
    onShow() {
        getUserTempCarList().then((res) => {

        })
    },
    mounted() {
        eventBus.$on("SET_TEMP_CART", (msg) => {
            if (msg) {
                this.list = msg
            }
        })
        // 获取专款专项额度
        GetAccountBalance().then((res) => {
            this.DeclarationBalance = res?.Data?.DeclarationBalance;
        })
        // 获取产品线
        GetUserProductLine().then((res) => {
            if (res?.Data?.LineIds?.length > 0) {
                this.ProductLineIds = res.Data.LineIds;
                GetProductCategoryListByLine({
                    lines: res.Data.LineIds,
                    isPointReward: -1,
                    level: 2,
                }).then((res) => {
                    this.classifyList = []
                    res.Data.forEach((item, index) => {
                        if (index == 0) {
                            this.activeId = item.id
                            this.requestData.typePath = item.parent_path
                        }
                        var totalClassify = {
                            OrderBy: item.orderBy,
                            id: item.id,
                            name: item.name,
                            parent_id: item.parent_id,
                            parent_path: item.parent_path,
                            type_id: item.type_id,
                            level: 3,
                            time: new Date(),
                        }
                        this.classifyList.push(totalClassify)
                    })
                    // setTimeout(() => {
                    //     this.refresh()
                    // }, 300)
                })
            } else {
                uni.showToast({
                    title: "未开通授限，请联系业务办理",
                    icon: "none",
                })
                setTimeout(() => {
                    this.easyReLaunchToHome()
                }, 2000)
            }
        })
        if (getPlatform() == "ios") {
            this.isIos = true
        } else {
            this.isIos = false
        }
        this.getListHeight()
        // 获取整体显示设置
        this.GetProductDisplay()
    },
    methods: {
        // 获取整体显示设置
        GetProductDisplay() {
            getProductDisplay().then((res) => {
                if (res) {
                    this.displayData = res.Data
                    if (this.displayData.IsShowImg) {
                        this.actions = [
                            {
                                type: "icon-youtu",
                                id: 3,
                                iconType: 3,
                            },
                        ]
                    } else {
                        this.actions = [
                            {
                                type: "icon-wutu",
                                id: 3,
                                iconType: 3,
                            },
                        ]
                    }
                }
            })
        },
        getListHeight(isHome = false) {
            //获取商品高度
            getElementHeight(this, ".main-dom", (e) => {
                console.log(e)
                e = e - 60 // 扣除购物车底部高度
                e = isHome ? e - 54 : e
                this.initHeight = e
                this.listHeight = e + "px"
                if (this.isIos) {
                    this.listHeight1 = e - 62 + "px"
                    this.listHeight2 = e - 62 + "px"
                } else {
                    this.listHeight1 = e - 32 + "px"
                    this.listHeight2 = e - 32 + "px"
                }
                this.loadOk = true
            })
        },
        searchFn(searchText) {
            //搜索
            this.requestData.search = searchText
            this.refresh()
        },
        // 展示临时购物车
        openCart() {
            this.$refs.popCarTip.open()
        },
        // 提交订单
        sunbmitOrder(totalPrice) {
            // todo orderType：4 专款
            if (this.DeclarationBalance == 0) {
                uni.showToast({
                    title: "您的提货额度已用完，请联系业务办理",
                    icon: "none",
                })
            } else if (totalPrice > this.DeclarationBalance) {
                uni.showToast({
                    title: "您的专款余额不足，请联系业务办理",
                    icon: "none",
                })
            } else {
                this.easyGoTo("/pages_supplier/packet/order/submitOrder?isTempCar=1&orderType=4")
            }
        },
        //刷新列表
        refresh() {
            this.$refs.swiperIndex.refresh(this.requestData)
        },
        // 点击分类事件
        treeClickEvent(item) {
            if (this.activeId !== item.id) {
                this.requestData.typePath = item.parent_path
                this.typePath = item.parent_path
                this.activeId = item.id
                this.refresh()
            }
        },
        sku(item) {
            this.showPopSku = true
            this.optPopup.type = "attr"
            this.optPopup.data = item
            this.$refs.popSku.open()
        },
        // 关闭输入数量弹窗
        popAmountClose() {
            this.$refs.popAmountTip.close()
            this.blurFn()
        },
        // 输入数量弹窗确认
        popAmountConfirm() {
            if (this.popite.Ratio == 1 && (this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum) > 0) {
                if (this.isInteger(this.popinputAmount, this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum)) {
                    this.inputAmount = this.popinputAmount
                    this.popite.Amount = this.popinputAmount
                    this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
                } else {
                    this.easyToast("请输入" + (this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum) + "的倍数")
                }
            } else {
                this.inputAmount = this.popinputAmount
                this.popite.Amount = this.popinputAmount
                this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
            }
        },
        // 改变输入数量
        async changeAmountFn(item, ite, type, popdisplayData) {
            var that = this
            let num = item.Amount
            let stock = item.Stock
            let UnitRatio = item.Ratio
            let minNum = 0
            let addNum = 1
            let LimitBuy = 0
            if (ite.ProductSkuList[0].MinimumOrder > 0) {
                minNum = ite.ProductSkuList[0].MinimumOrder
            } else {
                minNum = ite.MinNum
            }
            if (ite.ProductSkuList[0].AddNum > 0) {
                addNum = ite.ProductSkuList[0].AddNum
            } else {
                addNum = item.Ratio && UnitRatio == 1 ? ite.AddNum : 1
            }
            if (ite.ProductSkuList[0].LimitBuy > 0) {
                LimitBuy = ite.ProductSkuList[0].LimitBuy
            } else {
                LimitBuy = ite.LimitBuy
            }
            const _oldAmount = item.Amount

            if (popdisplayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type)
                } else {
                    item.Amount = num
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.poprefresh = true
            this.$nextTick(() => {
                this.poprefresh = false
            })
            this.$forceUpdate()
            this.isUpNum(false)
            //商品
            if (_oldAmount !== item.Amount || type === 0) {
                let carResult = await getUserCarList({ isTempCar: true });
                let param = [];
                let carData = carResult.Data || [];
                if (carData.length > 0) {
                    carData.forEach((item) => {
                        param.push({
                            ProductId: item.ProductId,
                            Amount: item.Amount,
                            SkuId: item.SkuId,
                            UnitId: item.UnitId,
                            UnitName: item.UnitName,
                            Ratio: item.Ratio,
                        })
                    })
                }
                let index = param.findIndex(e => e.ProductId == item.ProductId && e.SkuId == item.SkuId && e.UnitId == item.UnitId)
                param[index].Amount = item.Amount
                updateCart(param, false, true, this.orderType, "", true).then((res) => { })
            }
            setTimeout((e) => {
                that.$refs.popAmountTip.close()
                this.blurFn()
            }, 500)
        },
        blurFn() {
            this.$nextTick(() => {
                this.isFocus = false
                this.selectionStart = -1
                this.selectionEnd = -1
            })
        },
        // 清空购物车
        async clearCart() {
            let carResult = await getUserCarList({ isTempCar: true });
            let param = [];
            let carData = carResult?.Data || [];
            if (carData.length > 0) {
                carData.forEach((item) => {
                    param.push({
                        ProductId: item.ProductId,
                        Amount: 0,
                        SkuId: item.SkuId,
                        UnitId: item.UnitId,
                        UnitName: item.UnitName,
                        Ratio: item.Ratio,
                    })
                })
            }
            updateCart(param, false, true, this.orderType, "", true).then((res) => {
                this.$forceUpdate();
                uni.showToast({
                    title: "操作成功",
                    icon: "success",
                })
                this.$refs.popCarTip.close();
            })
        },
        amountProp(ite, item, type, displayData) {
            this.popite = ite
            this.popitem = item
            this.poptype = type
            this.popdisplayData = displayData
            if (ite.Amount == 0) {
                this.popinputAmount = 0
            } else {
                this.popinputAmount = ite.Amount
            }
            this.$refs.popAmountTip.open()
            setTimeout((e) => {
                this.isFocus = true
                this.selectionStart = 0
                this.selectionEnd = this.popinputAmount.toString().length
            }, 100)
        },
        // 收藏触发更新
        upFavorite(infoType) {
            if (infoType == 2) {
                if (this.$refs.productList_0 && this.$refs.productList_0[0]) {
                    this.$refs.productList_0[0].refresh(this.requestData)
                }
            } else if (infoType == 0) {
                if (this.$refs.productList_2 && this.$refs.productList_2[0]) {
                    this.$refs.productList_2[0].refresh(this.requestData)
                }
            }
        },
        isUpNum(e) {
            this.isUp = e
        },
        loadNoMoreBack(e) {
            if (e) {
                let objItem = {}
                let hasIn = false

                if (!this.classifyList || this.classifyList.length < 1) {
                    return
                }
                if (this.activeId == this.classifyList[0].id) {
                    //当前是全部分类
                    this.classifyList[1].expand = true
                    this.treeClickEvent(this.classifyList[1])
                } else {
                    for (var i = 0; i < this.classifyList.length; i++) {
                        let item = this.classifyList[i]
                        if (item.id == this.activeId) {
                            //判断当前是否是大类
                            this.hasIn = true
                            if (i != this.classifyList.length - 1) {
                                objItem = this.classifyList[i + 1]
                            } else {
                                objItem = this.classifyList[0]
                            }
                            this.classifyList.forEach((e) => {
                                if (e.id == objItem.id) {
                                    e.expand = true
                                } else {
                                    e.expand = false
                                }
                            })
                            this.treeClickEvent(objItem)
                            return
                        } else {
                            if (item.children) {
                                for (var j = 0; j < item.children.length; j++) {
                                    let subitem = item.children[j]
                                    if (subitem.id == this.activeId) {
                                        if (j != item.children.length - 1) {
                                            objItem = item.children[j + 1]
                                        } else {
                                            if (i != this.classifyList.length - 1) {
                                                objItem = this.classifyList[i + 1]
                                            } else {
                                                objItem = this.classifyList[0]
                                            }
                                            this.classifyList.forEach((e) => {
                                                if (e.id == objItem.id) {
                                                    e.expand = true
                                                } else {
                                                    e.expand = false
                                                }
                                            })
                                        }
                                        this.treeClickEvent(objItem)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    if (!hasIn) {
                        for (var i = 1; i < this.classifyList.length; i++) {
                            let item = this.classifyList[i]
                            let path = item.parent_path
                            if (this.typePath.includes(path)) {
                                let item = this.classifyList[i]
                                if (i != this.classifyList.length - 1) {
                                    objItem = this.classifyList[i + 1]
                                } else {
                                    objItem = this.classifyList[0]
                                }
                                this.classifyList.forEach((e) => {
                                    if (e.id == objItem.id) {
                                        e.expand = true
                                    } else {
                                        e.expand = false
                                    }
                                })
                                this.treeClickEvent(objItem)
                                return
                            }
                        }
                    }
                }
            }
        },
        skuChange(e) {
            if (!e.show) {
                this.showPopSku = false
                // this.$nextTick(e=>{
                // 	this.showPopSku = true
                // })
            }
        },
        changeProductData(product) {
            this.optPopup.data = product
            this.optPopup.change = true
        },
        closePopup() {
            this.$refs.popSku.close()
        },
        addCart(e) {
            this.$refs.popSku.close()
        },
        addBatch(e) {
            this.$refs.popSku.close()
            this.$refs.popBatch.open()
        },
        setCarListFunc() {
            this.$forceUpdate()
        },
        pormotionFn(e) {//促销列表
            this.pormotionData = e;
            this.$refs.policyPop.open()
        },
    },
}
</script>
<style lang="scss">
.header-wrapper {
    height: 120rpx;
    padding: 12rpx 0 24rpx 32rpx;
    box-sizing: border-box;
    background-color: $app-color-main;
    color: $color-white;
    font-size: 24rpx;

    .title {
        margin-bottom: 16rpx;
    }

    .balance {
        font-size: 32rpx;
        font-weight: bold;
    }
}

.product-main {
    display: flex;
    flex-direction: row;

    .product-main-nav {
        display: flex;
        flex: 1.3;
        flex-direction: column;
        // background: $uni-bg-color-grey;
        position: relative;
        z-index: 10;
        overflow-y: scroll;
    }

    .product-main-list {
        // display: flex;
        flex: 3.5;
        // justify-content: center;
        background: $uni-bg-color-grey;
        position: relative;
        z-index: 1;
        margin-left: -8rpx;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}

// 弹窗组件
.popup-content {
    width: auto;
    display: flex;
    flex-direction: column;
    position: relative;
    background: #f5f5f5;
    border-radius: 40rpx 40rpx 0 0;
    padding-right: $app-page-padding;
    padding-left: $app-page-padding;
    padding-bottom: 120rpx;
    z-index: 0;

    .popup-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;

        .popup-title-text {}

        .popup-title-action {}
    }

    .scroll {
        max-height: 700rpx;

        .cart-item {
            background: $color-white;
            padding: 0 $app-page-padding;
            border-radius: $border-radius-10;
            margin-bottom: 20rpx;
        }
    }
}
</style>
